//
//  LoginViewController.m
//  IMHX_Demo
//
//  Created by 郭健 on 16/3/31.
//  Copyright © 2016年 海城. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "CurrentUserInfo.h"
#import "AppDelegate.h"
//#import "MainTabBarController.h"
#import "RootViewController.h"




@interface LoginViewController ()
@property (nonatomic ,strong)UITextField *userName;
@property (nonatomic ,strong)UITextField *passWord;
@property (nonatomic ,strong)UIImageView *myHeaderImage;
@property (nonatomic ,strong)UIButton *loginBtn;
@property (nonatomic ,strong)UIButton *registeredBtn;
@property (nonatomic ,strong)UIImageView *userNameImage;     //用户名图片
@property (weak, nonatomic) IBOutlet UIImageView *passWordImage;        //密码图片

@property (nonatomic,retain)UIActivityIndicatorView *activityIndicatorView;     //加载小菊花

@end

@implementation LoginViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.navigationItem.title = @"登  录";
    [self loginBlurEffect];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"注 册" style:UIBarButtonItemStylePlain target:self action:@selector(registeredClick)];
    
}

//视图即将出现
- (void)viewWillAppear:(BOOL)animated {
    
    self.navigationController.navigationBarHidden = YES;
}

#pragma mark -- 懒加载
-(UITextField *)userName{
    
    if (!_userName) {
        _userName = [[UITextField alloc]initWithFrame:CGRectMake(0, kHeight / 3, kWidth, 40)];
        _userName.borderStyle = UITextBorderStyleRoundedRect;
        _userName.placeholder = @"用户名/邮箱";
        _userName.textAlignment = NSTextAlignmentCenter;
    }
    return _userName;
}
-(UITextField *)passWord{
    
    if (!_passWord) {
        _passWord = [[UITextField alloc]initWithFrame:CGRectMake(0, kHeight / 3 + 40, kWidth, 40)];
        _passWord.borderStyle = UITextBorderStyleRoundedRect;
        _passWord.placeholder = @"密码";
        _passWord.textAlignment = NSTextAlignmentCenter;
    }
    return _passWord;
}
-(UIImageView *)myHeaderImage{
    
    if (!_myHeaderImage) {
        _myHeaderImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"logo.jpeg"]];
        _myHeaderImage.frame = CGRectMake(kWidth / 2 - 42, kHeight /6, 80, 80);
        _myHeaderImage.layer.cornerRadius = _myHeaderImage.frame.size.width/2;
        _myHeaderImage.clipsToBounds = YES;
    }
    return _myHeaderImage;
}
-(UIButton *)loginBtn{
    
    if (!_loginBtn) {
        _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginBtn.frame = CGRectMake(0, kHeight /3 + 40 +60, kWidth, 40);
        _loginBtn.backgroundColor = [UIColor grayColor];
        _loginBtn.layer.cornerRadius = 5;
        _loginBtn.clipsToBounds = YES;
        [_loginBtn setTitle:@"登 录" forState:UIControlStateNormal];
        [_loginBtn addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginBtn;
}

-(UIButton *)registeredBtn{

    if (!_registeredBtn) {
        _registeredBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _registeredBtn.frame = CGRectMake(0, kHeight /3 + 40 +60 + 60, kWidth, 40);
        _registeredBtn.backgroundColor = [UIColor grayColor];
        _registeredBtn.layer.cornerRadius = 5;
        _registeredBtn.clipsToBounds = YES;
        [_registeredBtn setTitle:@"注 册" forState:UIControlStateNormal];
        [_registeredBtn addTarget:self action:@selector(registeredClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _registeredBtn;

}

-(UIActivityIndicatorView *)activityIndicatorView{

    if (!_activityIndicatorView) {
        _activityIndicatorView = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
        _activityIndicatorView.center = self.view.center;
        _activityIndicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
        [self.view addSubview:_activityIndicatorView];
    }
    return _activityIndicatorView;
}





#pragma mark -- 毛玻璃功能
-(void)loginBlurEffect{
    
    UIImageView *imageView  = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"bg_2-1.png"]];
    imageView.userInteractionEnabled = YES; 
    imageView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    NSLog(@"%@",NSStringFromCGRect(self.view.frame));
    [self.view addSubview:imageView];
    
    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc]initWithEffect:blur];
    effectView.alpha = 0.3;
    effectView.frame = CGRectMake(0, 0, imageView.frame.size.width, imageView.frame.size.height);
    [imageView addSubview:effectView];
    
    [imageView addSubview:self.userName];
    [imageView addSubview:self.passWord];
    [imageView addSubview:self.myHeaderImage];
    [imageView addSubview:self.loginBtn];
    [imageView addSubview:self.registeredBtn];
}


#pragma mark -- 按钮的回调方法

-(void)registeredClick{
    
    RegisterViewController *registerVC = [[RegisterViewController alloc]init];
    [self.navigationController pushViewController:registerVC animated:YES];
    self.navigationController.navigationBarHidden = NO;
}

-(void)loginBtnClick:(NSString *)name{
    
    NSLog(@"登录成功");
    
}
    //*登录按钮*/
-(void)loginBtnClick{

    //判断是否为空
    if (![self loginNull]) {        //用户名或者密码为空
        return;
    }
    
    //开启动画
    [self.activityIndicatorView startAnimating];
    //弹出提醒
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
       
        EMError *error = [[EMClient sharedClient] loginWithUsername:self.userName.text password:self.passWord.text];
        [AVUser logInWithUsernameInBackground:self.userName.text password:self.passWord.text block:^(AVUser *user, NSError *error) {
            
            NSLog(@"---------leanClound登录%@",user.username);
        }];
        if (!error) {
            NSLog(@"登陆成功");
            //将用户信息存储到本地
            CurrentUserInfo *userInfo = [CurrentUserInfo sharedCurrentUserInfo];
            userInfo.userName = self.userName.text;
            userInfo.pwd = self.passWord.text;
            userInfo.isLogin = YES;
            
            //自动登录
            [[EMClient sharedClient].options setIsAutoLogin:YES];
            
            if (self.state == fromMainViewControllerState) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self dismissViewControllerAnimated:YES completion:nil];
                });
            }else{      //打开app就是登录界面,这个时候，loginVC就是Window的根视图控制器，当登录成功的时候，我们应该更换window的根视图控制器为主界面控制器
            
                dispatch_async(dispatch_get_main_queue(), ^{
                    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
                    
                    RootViewController *mainTabBarController = [[RootViewController alloc]init];
                    appDelegate.window.rootViewController = mainTabBarController;
                    
                });
            }
            
        }else{
            NSLog(@"登录失败 -- %d",error.code);
            dispatch_async(dispatch_get_main_queue(), ^{
               
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"登录失败,请重新查看已输入的内容" preferredStyle:UIAlertControllerStyleActionSheet];
                
                //初始化一个按钮
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                
                
                [alertController addAction:action];
                
                [self presentViewController:alertController animated:YES completion:nil];
            });
        }
    
        dispatch_async(dispatch_get_main_queue(), ^{
            
            //弹出提醒消失
            [self.activityIndicatorView stopAnimating];
            //动画移除
            [self.activityIndicatorView removeFromSuperview];
        });
    });
}


    /**注册按钮*/
-(void)regisertAction{
  
    RegisterViewController *registerVC = [[RegisterViewController alloc]init];
    [self.navigationController pushViewController:registerVC animated:YES];

    }

#pragma mark -- 判断方法
//判断账号密码是否为空
-(BOOL)loginNull{
    
    if (self.userName.text.length == 0) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"账号不能为空" preferredStyle:UIAlertControllerStyleActionSheet];
        
        //初始化一个按钮
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        
        
        [alertController addAction:action];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
        NSLog(@"用户名不能为空");
        return NO;
    }else if (self.passWord.text.length == 0){
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"密码不能为空" preferredStyle:UIAlertControllerStyleActionSheet];
        
        //初始化一个按钮
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        
        
        [alertController addAction:action];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
        NSLog(@"密码不能为空");
        return NO;
    }
    return YES;
}

//判断自动登录
-(BOOL)autoLogin{

    BOOL isAutoLogin = [EMClient sharedClient].options.isAutoLogin;
    if (!isAutoLogin) {
        EMError *error = [[EMClient sharedClient] loginWithUsername:@"1111" password:@"1111"];
    }
    return YES;
}

//键盘回收
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
